import { Raycaster, Vector2 } from "three";

export default function createSelectEvent(config) {
    const { models, renderer } = config.framework;
    let isMultiple = false;
    let raycaster = new Raycaster(); // 重用Raycaster实例

    // 设置选择类型
    config.setSelectType = function(types) {
        config.selectType = types;
        if (config.modelEvent) {
            config.modelEvent.selectedModelAll(false);
        }
        config.pointAttrMethods?.resetHighlight();
    };

    // 键盘事件监听
    function handleKeyEventListener(event) {
        if (event.key === 'Control' || event.key === 'Meta') { // 支持Ctrl和Cmd键
            isMultiple = event.type === 'keydown';
        }
    }

    // 事件监听器管理
    function handleEventListener(enable) {
        if (enable) {
            renderer.domElement.addEventListener("pointerdown", handleClick);
            renderer.domElement.addEventListener('dblclick', handleDoubleClick);
            window.addEventListener('keydown', handleKeyEventListener);
            window.addEventListener('keyup', handleKeyEventListener);
        } else {
            renderer.domElement.removeEventListener("pointerdown", handleClick);
            renderer.domElement.removeEventListener('dblclick', handleDoubleClick);
            window.removeEventListener('keydown', handleKeyEventListener);
            window.removeEventListener('keyup', handleKeyEventListener);
        }
    }

    // 获取标准化设备坐标
    function getNormalizedCoordinates(event) {
        const rect = renderer.domElement.getBoundingClientRect();
        return new Vector2(
            ((event.clientX - rect.left) / rect.width) * 2 - 1,
            -((event.clientY - rect.top) / rect.height) * 2 + 1
        );
    }

    // 处理点击事件
    function handleClick(event) {
        const { camera } = config.framework
        const pointer = getNormalizedCoordinates(event);
        raycaster.setFromCamera(pointer, camera);

        // 查找模型和点
        const clickModel = []
        const partModel = models.children.find(item => item.userData.isPartBox);
        const pointModel = models.children.find(item => item.userData.isPoint);

        let isSelectPoint = config.selectType.includes("point")
        let isSelectPart = config.selectType.includes("model")

        if (isSelectPoint && pointModel) {
            clickModel.push(pointModel)
        }

        if (isSelectPart && partModel) {
            clickModel.push(partModel)
        }

        let intersects = raycaster.intersectObjects(clickModel)
        console.log(intersects)
        if (intersects.length > 0) {
            let intersect = intersects[0];
            if (isSelectPoint && intersect.object.userData.isPoint) {
                config.pointAttrMethods.handlePointClick(intersect.instanceId, isMultiple);
                return
            }
            if (isSelectPart && config.modelEvent.findParentPartBox(intersect.object.uuid)) {
                config.modelEvent.setSelectedModel(intersect.object.uuid, isMultiple);
                return
            }
        }

        if (isMultiple) return
        // 没有选中任何东西时的处理
        if (config.selectType.includes("model")) {
            config.modelEvent.resetAllHighlight();
        }
        if (config.selectType.includes("point")) {
            config.pointAttrMethods.resetHighlight();
        }
    }

    // 处理双击事件
    function handleDoubleClick(event) {
        if (!config.selectType.includes("model")) return;
        const { camera } = config.framework

        const pointer = getNormalizedCoordinates(event);
        raycaster.setFromCamera(pointer, camera);

        const partModel = models.children.find(item => item.userData.isPartBox);
        const intersects = partModel ? raycaster.intersectObject(partModel) : [];

        config.modelEvent.selectedModelAll(intersects.length > 0);
    }

    return handleEventListener;
}